TGTDIR := ../build/
TARGET := $(TGTDIR)kernel
SRC := $(wildcard *.c)
ASMSRC := $(wildcard *.S)
SUBOBJS = $(filter %.o, $(patsubst ./%, %.o, $(shell find -maxdepth 1 -type d)))
OBJS = $(patsubst %.S, $(TGTDIR)%.o, $(ASMSRC))
OBJS += $(patsubst %.c, $(TGTDIR)%.o, $(SRC))
OBJS += $(patsubst %.o, $(TGTDIR)%.o, $(SUBOBJS))

export ECHOPRE := @
export TOOLPREFIX = /opt/cross-tools/bin/loongarch64-unknown-linux-gnu-

export CC = $(TOOLPREFIX)gcc
export LD = $(TOOLPREFIX)ld

export CFLAGS = -Wall -O2 -g3 \
	-march=loongarch64 -mabi=lp64s \
	-ffreestanding -fno-common \
	-nostdlib \
	-I../include \
	-fno-stack-protector \
	-fno-pie -no-pie 

export LDFLAGS = -z max-page-size=4096


$(TARGET): $(OBJS) ld.script
	@echo LD $(TARGET)
	$(ECHOPRE)$(LD) $(LDFLAGS) -T ld.script -o $(TARGET) $(OBJS)

$(TGTDIR)%.o : %.c
	@echo CC $<
	$(ECHOPRE)$(CC) $(CFLAGS) -c -o $@ $<

$(TGTDIR)%.o : %.S
	@echo CC $<
	$(ECHOPRE)$(CC) $(CFLAGS) -c -o $@ $<

$(TGTDIR)%.o :
	@echo CD $(subst .o,,$@) 
	@mkdir -p $(subst .o,,$@)
	@(cd $(subst $(TGTDIR),,$(subst .o,,$@)); make)


.PHONY: clean
clean: 
	rm -rf build/
